package com.enjoylearning.content.service.Impl;

import com.enjoylearning.content.mapper.CourseCategoryMapper;
import com.enjoylearning.content.service.CourseCategoryService;
import com.enjoylearning.content.model.dto.CourseCategoryTreeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        return addNodes(id, courseCategoryTreeDtos);
    }

    public List<CourseCategoryTreeDto> addNodes(String id, List<CourseCategoryTreeDto> courseCategoryTreeDtos) {
        List<CourseCategoryTreeDto> result = new ArrayList<>();
        //对数据进行遍历
        for (CourseCategoryTreeDto courseCategoryTreeDto : courseCategoryTreeDtos) {
            //当数据的父节点等于根节点时，先对其子节点进行递归构建
            if (courseCategoryTreeDto.getParentid().equals(id)) {
               /* //防止空指针
                if (courseCategoryTreeDto.getChildrenTreeNodes() == null) {
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<>());
                }*/
                //递归构建当前数据的子节点，并赋值给父节点
                List<CourseCategoryTreeDto> courseCategoryTreeDtos1 = addNodes(courseCategoryTreeDto.getId(), courseCategoryTreeDtos);
                //若子节点未进行填充，则设置为NULL
                if (courseCategoryTreeDtos1.isEmpty()) {
                    courseCategoryTreeDtos1 = null;
                }
                courseCategoryTreeDto.setChildrenTreeNodes(courseCategoryTreeDtos1);
                //将所有的二级节点（父节点）放入队列中
                result.add(courseCategoryTreeDto);
            }
        }
        return result;
    }
}
